package com.sysmanage.permissions.controls;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sysmanage.framework.controls.struts2.BaseTg;
import com.sysmanage.permissions.model.Company;
import com.sysmanage.permissions.model.Department;
import com.sysmanage.permissions.service.ICompanyService;
import com.sysmanage.permissions.service.IDepartmentService;
import com.sysmanage.permissions.tree.Utils;
import com.sysmanage.tree.Node;
import com.sysmanage.tree.UncodeException;
import com.sysmanage.tree.UserDataUncoder;
import com.sysmanage.tree.support.AbstractWebTreeModelCreator;
import com.sysmanage.tree.support.WebTreeNode;


/** 
  * @ClassName: DepartmentTg 
  * @Description: 公司信息控制层
  * @author XXXX@163.com
  * @date 2011-9-26 上午9:12:04 
  *  
  */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("permissions.departmentControl")
public class DepartmentTg extends BaseTg {
	/** 
	  * @Fields departmentService : IDepartmentService接口spring注入 
	  */ 
	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private ICompanyService companyService;



	/** 
	  * @Fields department : struts2.0自动接受
	  */ 
	private Department department;
	
	/** 
	  * @Fields id : 要删除的id
	  */ 
	private String id;
	/** 
	  * @Fields deptid : 被加到的部门
	  */ 
	private String deptid;
	
	
	public void getTree(){
		List<Map<String,Object>> list = this.departmentService.getTree(id);
		outJsonPlainString(response, JSONArray.fromObject(list).toString());
	}
	
	
	/** 
	  * @Title: all 
	  * @Description: 获得所有的公司
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void all(){
		List<Department> list = departmentService.getAll();
		JSONArray jsonArray = JSONArray.fromObject(doOther(list));
		returnJsion(jsonArray.toString(),response);
	}
	
	/** 
	  * @Title: update 
	  * @Description: 更新公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void update(){
		if(this.departmentService.alter(department)){
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	
	/** 
	  * @Title: find 
	  * @Description: 根据id查找公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void find(){
		Department department = this.departmentService.findById(Integer.valueOf(id));
		List<Department> list = new ArrayList<Department>();
		if(null != department){
			list.add(department);
		}
		JSONArray jsonArray = JSONArray.fromObject(doOther(list));
		
		if(null != department.getParentId()){
			Department temp = this.departmentService.findById(Integer.valueOf(department.getParentId()));
			if(temp!=null)
			{
				returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"" + temp.getId() + "\",\"parentName\":\"" + temp.getDeptName() + "\"}",response);
			}
			else{
				returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"\"}",response);
			}
		}else{
			returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"\"}",response);
		}
	}
	
	/** 
	  * @Title: del 
	  * @Description: 根据id删除公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void del(){
		if(this.departmentService.deleteById(Integer.valueOf(id))){
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	
	/** 
	  * @Title: save 
	  * @Description: 保存一条公司的记录
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void save(){
		if(this.departmentService.save(department)){
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	
	/** 
	  * @Title: list 
	  * @Description: 获取所有公司，并且用tree来显示
	  * @param @return
	  * @return String 一段<html>代码
	  * @throws 
	  */
	public void list(){
		List<Department> list = departmentService.getAll();
		// 业务数据解码器，从业务数据中分解出id和parentid
		UserDataUncoder orgUncoder = new UserDataUncoder() {
			public Object getID(Object pUserData) throws UncodeException {
				Department org = (Department) pUserData;
				return org.getId();
			}

			public Object getParentID(Object pUserData) throws UncodeException {
				Department org = (Department) pUserData;
				return org.getParentId();
			}
		};

		// Tree模型构造器，用于生成树模型
		AbstractWebTreeModelCreator treeModelCreator = new AbstractWebTreeModelCreator() {
			// 该方法负责将业务数据映射到树型节点
			protected Node createNode(Object pUserData, UserDataUncoder pUncoder) {
				Department org = (Department) pUserData;
				WebTreeNode result = new WebTreeNode(org.getDeptName(), "node"+org.getId(),org);

				return result;
			}
		};
		String temp = Utils.showeasyuiTree(orgUncoder, treeModelCreator, list, request);
		outHtmlUTFString(response,temp);
	}

	/** 
	  * @Title: index 
	  * @Description: 组的首页信息
	  * @param @return
	  * @return String
	  * @throws 
	  */
	public String index(){
		List<Department> list = departmentService.getAll();
		// 业务数据解码器，从业务数据中分解出id和parentid
		UserDataUncoder orgUncoder = new UserDataUncoder() {
			public Object getID(Object pUserData) throws UncodeException {
				Department org = (Department) pUserData;
				return org.getId();
			}

			public Object getParentID(Object pUserData) throws UncodeException {
				Department org = (Department) pUserData;
				return org.getParentId();
			}
		};

		// Tree模型构造器，用于生成树模型
		AbstractWebTreeModelCreator treeModelCreator = new AbstractWebTreeModelCreator() {
			// 该方法负责将业务数据映射到树型节点
			protected Node createNode(Object pUserData, UserDataUncoder pUncoder) {
				Department org = (Department) pUserData;
				WebTreeNode result = new WebTreeNode(org.getDeptName(), "node"+org.getId(),org);
				return result;
			}
		};
		String temp = Utils.showeasyuiTree(orgUncoder, treeModelCreator, list, request);
		request.setAttribute("treeScript", temp);
		return this.SUCCESS;
	}

	/** 
	  * @Title: returnJsion 
	  * @Description: 解决json问题
	  * @param @param baseStr
	  * @param @param response
	  * @return void
	  * @throws 
	  */
	private void returnJsion(String baseStr, HttpServletResponse response) {
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(baseStr);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
		
	}
	
	/** 
	  * @Title: doOther 
	  * @Description: 解决struts2.0domal接受参数的方法
	  * @param @param list 装Groups的具体信息。
	  * @param @return
	  * @return List
	  * @throws 
	  */
	private List doOther(List<Department> list) {
		List lists = new ArrayList();
		if(list != null && list.size() > 0){
			Company tmp = null;
			for(int i =0;i<list.size();i++){
				Map<String,String> map = new HashMap<String, String>();
				Department department = list.get(i);
				map.put("id", department.getId() + "");
				map.put("deptName", department.getDeptName());
			
				map.put("companyId", department.getCompanyId()+"");
				if(department.getCompanyId()!=null)
				{
					tmp = companyService.findById(department.getCompanyId());
					if(tmp!=null)
					{
						map.put("companyName",tmp.getCompanyName());
					}
					else
					{
						map.put("companyName","");
					}
				}
				else
				{
					map.put("companyName","");
				}
				map.put("orderId", department.getOrderId());
				map.put("status", department.getStatus()+"");
				lists.add(map);
			}
		}else{
			Map<String,String> map = new HashMap<String, String>();
			map.put("error", "error");
			lists.add(map);
		}
		return lists;
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}


	public IDepartmentService getDepartmentService() {
		return departmentService;
	}


	public void setDepartmentService(IDepartmentService departmentService) {
		this.departmentService = departmentService;
	}


	public Department getDepartment() {
		return department;
	}


	public void setDepartment(Department department) {
		this.department = department;
	}


	public String getDeptid() {
		return deptid;
	}


	public void setDeptid(String deptid) {
		this.deptid = deptid;
	}
	public ICompanyService getCompanyService() {
		return companyService;
	}


	public void setCompanyService(ICompanyService companyService) {
		this.companyService = companyService;
	}	
}
